<?php
/**
 * Created by PhpStorm.
 * User: 25791
 * Date: 2020/7/3
 * Time: 10:28
 * Note: sms_push.php
 */

namespace app\lib;


use Ext\libHttp;
use Ext\libLog;

class sms_push extends base
{
    public $url = "https://api.jpush.cn/v3/push";

    public $key = "c1745e62c519dd53c897f70e:75c8ca2a5771b87e092f3906";

    public $data = [
        "platform"     => "all",
        "audience"     => [],
        "notification" => [
            "android" => [
                "alert" => '',
                "title" => "松鼠帮帮",
            ],
            "ios"     => [
                "alert" => '',
            ],
        ],
    ];

    /**
     * 给单个用户推送消息
     *
     * @param string $device_id
     * @param string $sms
     * @param int    $act_id
     * @param mixed  $extra_info
     *
     * @return string
     * @throws \Exception
     */
    public function push_one(string $device_id, string $sms, int $act_id = 0, $extra_info = '')
    {
        if (empty($device_id)) {
            return true;
        }
        $this->data['audience']                         = ["registration_id" => [$device_id]];
        $this->data['notification']['android']['alert'] = $sms;
        $this->data['notification']['ios']['alert']     = $sms;
        if ($act_id) {
            $this->data['notification']['android']["extras"] = ['act_id' => $act_id, 'extra_info' => $extra_info];
        }
        $base64_auth_string = base64_encode($this->key);
        $res = libHttp::new()
            ->addData($this->data)
            ->setContentType(libHttp::CONTENT_TYPE_JSON)
            ->setHttpMethod('POST')
            ->addHeader(['Authorization' => 'Basic ' . $base64_auth_string])
            ->fetch($this->url);
        libLog::new('push')->add($res)->save();
        return  $res;
    }

    /**
     * 给所有用户推送消息
     *
     * @param string $sms
     * @param int    $act_id
     *
     * @return string
     * @throws \Exception
     */
    public function push_all(string $sms, int $act_id = 0)
    {
        $this->data['audience']                         = "all";
        $this->data['notification']['android']['alert'] = $sms;
        $this->data['notification']['ios']['alert']     = $sms;
        if ($act_id) {
            $this->data['notification']['android']["extras"] = ['act_id' => $act_id];
        }
        $base64_auth_string = base64_encode($this->key);
        return libHttp::new()
            ->addData($this->data)
            ->setHttpMethod('POST')
            ->addHeader(['Authorization' => 'Basic ' . $base64_auth_string])
            ->fetch($this->url);
    }
}